﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GeoVision.BingMap.ImageryService;
using Microsoft.Maps.MapControl;
using System.Windows.Media.Imaging;
using GeoVision.BingMap.Windows;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
using System.Windows.Controls.Primitives;
using Microsoft.Maps.MapControl.PlatformServices;

namespace GeoVision.BingMap
{
    public partial class MainPage : UserControl
    {
        public static string ApplicationId { get; set; }
        ImageDialogWindow imgWindow;
        KeyInfoWindow keyInfo;
        Point firstPoint;
        Point endPoint;
        System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle();
        Microsoft.Maps.MapControl.Location polygonPointLocation1;
        bool mouseDown = false;
        Microsoft.Maps.MapControl.LocationCollection polygonList = new Microsoft.Maps.MapControl.LocationCollection();
        MapLayer polygonPointLayer = new MapLayer();

        public MainPage()
        {
            InitializeComponent();
            installBtn.Visibility = (Application.Current.InstallState == InstallState.NotInstalled ? Visibility.Visible : Visibility.Collapsed);
            canvasTop.Visibility = Visibility.Collapsed;
            btnFinish.IsEnabled = false;

        }
        private void btnSec_Click(object sender, RoutedEventArgs e)
        {
            canvasTop.Visibility = Visibility.Visible;
            this.Cursor = Cursors.Stylus;

        }

        private void btnRemove_Click(object sender, RoutedEventArgs e)
        {
            SecimiSil();
        }

        private MapStyle GetMapStyle()
        {
            if (MyMap.Mode is AerialMode)
            {
                return ((AerialMode)MyMap.Mode).Labels ? MapStyle.AerialWithLabels : MapStyle.Aerial;
            }
            else if (MyMap.Mode is RoadMode)
                return MapStyle.Road;
            else return MapStyle.Road;
        }

        private void installBtn_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Install();
        }

        private void GetImagery(double latitude, double longitude)
        {
            MapUriRequest mapUriRequest = new MapUriRequest();

            mapUriRequest.Credentials = new Credentials();
            mapUriRequest.Credentials.ApplicationId = ApplicationId;

            mapUriRequest.Center = new Location();
            mapUriRequest.Center.Latitude = latitude;
            mapUriRequest.Center.Longitude = longitude;

            MapUriOptions mapUriOptions = new MapUriOptions();
            mapUriOptions.Style = GetMapStyle();
            mapUriOptions.ZoomLevel = (int)MyMap.ZoomLevel;

            mapUriOptions.ImageSize = new ImageryService.SizeOfint();
            mapUriOptions.ImageSize.Height = (int)r.Height;
            mapUriOptions.ImageSize.Width = (int)r.Width;


            mapUriRequest.Options = mapUriOptions;

            ImageryServiceClient imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
            imageryService.GetMapUriCompleted += new EventHandler<GetMapUriCompletedEventArgs>(imageryService_GetMapUriCompleted);
            imageryService.GetMapUriAsync(mapUriRequest);


        }

        void imageryService_GetMapUriCompleted(object sender, GetMapUriCompletedEventArgs e)
        {
            MapUriResponse mapUriResponse = e.Result;
            imgWindow = new ImageDialogWindow(mapUriResponse.Uri);
            imgWindow.xbusy.IsBusy = true;
            imgWindow.Show();
            imgWindow.InitImage();

            imgWindow.Closed += (s, ez) =>
             {
                 SecimiSil();
             };

        }
        private void canvasTop_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MyMap.IsEnabled = false;
            polygonPointLocation1 = MyMap.ViewportPointToLocation(new Point(e.StylusDevice.GetStylusPoints(MyMap)[0].X, e.StylusDevice.GetStylusPoints(MyMap)[0].Y));
            r.Fill = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
            r.Stroke = new SolidColorBrush(Colors.Red);
            r.StrokeThickness = 1;
            r.Width = 0;
            r.Height = 0;
            MyLayer.Children.Clear();
            MyLayer.AddChild(r, polygonPointLocation1);
            mouseDown = true;
            firstPoint = new Point(e.StylusDevice.GetStylusPoints(MyMap)[0].X, e.StylusDevice.GetStylusPoints(MyMap)[0].Y);
            txtAlt.Text = firstPoint.X.ToString();
            txtLong.Text = firstPoint.Y.ToString();
        }
        /// <summary>
        /// Burda mouse a göre kare cizdiriliyor seçim alanı
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvasTop_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseDown)
            {

                r.Width = Math.Abs(e.GetPosition(MyMap).X - firstPoint.X);
                txtWidth.Text = r.Width.ToString();
                r.Height = Math.Abs(e.GetPosition(MyMap).Y - firstPoint.Y);
                txtHeight.Text = r.Height.ToString();
                if (r.Width > 900)
                    r.Width = 900;
                if (r.Height > 935)
                    r.Height = 935;
                MyLayer.Children.Clear();
                MyLayer.AddChild(r, polygonPointLocation1);
            }
        }
        /// <summary>
        ///iki nokta arasındaki noktayı bulma işlemi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void canvasTop_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MyMap.IsEnabled = true;
            mouseDown = false;
            endPoint = new Point(e.StylusDevice.GetStylusPoints(MyMap)[0].X, e.StylusDevice.GetStylusPoints(MyMap)[0].Y);

            txtAlt2.Text = endPoint.X.ToString();
            txtLong2.Text = endPoint.Y.ToString();
            btnFinish.IsEnabled = true;
        }

        private void SecimiSil()
        {
            canvasTop.Visibility = Visibility.Collapsed;
            this.Cursor = Cursors.Arrow;
            MyLayer.Children.Clear();
            btnFinish.IsEnabled = false;
        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            ApplicationId = KeyInfoWindow.LoadData("BingKey");
            if (string.IsNullOrEmpty(ApplicationId))
            {
                keyInfo = new KeyInfoWindow();
                keyInfo.Show();
                keyInfo.Closed += (s, ze) =>
                {
                    if (!string.IsNullOrEmpty(ApplicationId))
                    {
                        SetKey();
                        KeyInfoWindow.SaveData(ApplicationId, "BingKey");
                    }
                };
            }
            else
                SetKey();
        }
        private void SetKey()
        {
            Microsoft.Maps.MapControl.Credentials cr = new Microsoft.Maps.MapControl.Credentials();
            cr.ApplicationId = ApplicationId;

            MyMap.CredentialsProvider = new ClientTokenCredentialsProvider(cr.ApplicationId);
        }

        private void btnFinish_Click(object sender, RoutedEventArgs e)
        {
            double x, y;
            x = firstPoint.X + Math.Abs(firstPoint.X - endPoint.X) / 2;
            y = firstPoint.Y < endPoint.Y ? Math.Abs(firstPoint.Y - endPoint.Y) / 2 + firstPoint.Y : Math.Abs(firstPoint.Y - endPoint.Y) / 2 + endPoint.Y;
            Point ortanokta = new Point(x, y);

            Microsoft.Maps.MapControl.Location result = MyMap.ViewportPointToLocation(ortanokta);
            if (double.Parse(txtWidth.Text) > 100 && double.Parse(txtHeight.Text) > 100)
                GetImagery(result.Latitude, result.Longitude);
            else
                MessageBox.Show(string.Format("The selected area must be greater than Height: 100 and Weight: 100"));
        }

        private void btnEnterKey_Click(object sender, RoutedEventArgs e)
        {
            keyInfo = new KeyInfoWindow();
            keyInfo.Show();
            keyInfo.Closed += (s, ze) =>
            {
                if (!string.IsNullOrEmpty(ApplicationId))
                {
                    SetKey();
                    KeyInfoWindow.SaveData(ApplicationId, "BingKey");
                }
            };
        }
    }
}
